package com.smyx.case3;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author SmyxCoding
 **/
public class CuratorLockTest {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            // 获取分布式锁
            InterProcessMutex mutexLock = new InterProcessMutex(obtainClient(), "/locks");
            int finalI = i;
            new Thread(() -> {
                try {
                    mutexLock.acquire();
                    System.out.println("线程" + finalI + " 获取到锁");
                    mutexLock.acquire();
                    System.out.println("线程" + finalI + " 再次获取到锁");
                    Thread.sleep(2 * 1000);
                    mutexLock.release();
                    System.out.println("线程" + finalI + " 释放锁");
                    mutexLock.release();
                    System.out.println("线程" + finalI + " 再次释放锁");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    private static CuratorFramework obtainClient() {
        ExponentialBackoffRetry policy = new ExponentialBackoffRetry(3000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder().connectString("vm110:2181,vm111:2181,vm112:2181")
                .connectionTimeoutMs(2000)
                .sessionTimeoutMs(2000)
                .retryPolicy(policy).build();
        // 启动客户端
        client.start();
        System.out.println("zookeeper 启动成功");
        return client;
    }
}
